package main

import "fmt"

func main() {
	ch := make(chan int)

	go func() {
		for i := 0; i < 8; i++ {
			ch <- i
		}
		close(ch) //写端，写完数据后，主动关闭channel
		//ch <- 10  //向关闭的channel写数据，会发生panic，panic: send on closed channel
	}()

	for {
		if num, ok := <-ch; ok {
			fmt.Println("读到数据，num = ", num)
		} else {
			n := <-ch
			fmt.Println("从关闭的channel中读取数据，n =", n) // 读到n = 0
			break
		}
	}

	// 第2种方式读channel中的数据
	//for num := range ch {
	//	fmt.Println(num)
	//}
}
